﻿using MicroMq.Helper;

using Microsoft.Extensions.DependencyInjection;

using MTP.Serialize;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MicroMq.Services
{
    class DelayPublishService : IHandlerService
    {
        private readonly DelayWorkService delayWorkService;

        public DelayPublishService(DelayWorkService delayWorkService)
        {
            this.delayWorkService = delayWorkService;
        }

        public byte HandleType => (byte)Models.HandleType.DelayPublish;

        public void Hanlder(PeerConnection connection, ByteReadBuffer readBuffer)
        {
            Publish(readBuffer.ReadUnknownString(), readBuffer.ReadInt(), readBuffer.ReadEnd());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="delay">延时单位秒</param>
        /// <param name="data"></param>
        public void Publish(string topic, int delay, byte[] data)
        {
            var buffer = ByteWriteBuffer.Alloc()
                .WriteUnknownString(topic)
                .Write(data)
                .ToBytes();
            delayWorkService.Enqueue(topic, buffer, delay);
        }
    }
}
